/*
 * @Author: wangtao
 * @Date: 2020-08-20 14:07:42
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-08-12 13:59:48
 * @Description: 司机端首页
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  TouchableOpacity,
  PixelRatio,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import {
  iconMainCoffee,
  iconMainGray,
  wlAgreementRightArrow,
  iconCloseOrange,
  sjfwText,
  iconChangeWhite,
  empty03,
} from '@/images';
import { msg, XMHeader, Button, _, XMEmpty } from '@/common';
import {
  mainBgColorLightGray,
  screenWidth,
  mainBgColorWhite,
  fontColorWhite,
  fontColorDeepRed,
  px2dp,
} from '@/styles';
import api from '@/api';
import OrderList from './components/order-list';
import DriverUncer from './components/driver-uncer';
import DriverUnTruck from './components/driver-untruck';
import DriverOutline from './components/driver-outline';
import ApplyLeave from './components/apply-leave';
import DriverBan from './components/driver-ban';
import InsuranceEntrance from './components/insurance_entrance';

const { Submit } = Button;

export default class CapacityMap extends React.Component {
  static navigationOptions = () => ({
    title: '首页',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconMainCoffee : iconMainGray}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      applyLeaveModelIsShow: false, // 申请请假弹框
      driverCerStatus: '', // 司机认证状态  0.未认证  1.未审核  2.已审核  3.审核失败
      driverCerData: '', // 司机认证返回数据
      driverCarList: null, // 司机车辆信息，如果为null，无车
      isLeave: true, // 是否请假  true:未请假 false:请假
      driverState: null, // 1销假 2请假
      carState: null, // 1销假 2请假
      leaveId: '', // 请假id,
      canLeave: true, // 是否可以请假  false代表不可以
      hasFace: false, // 是否已有人脸信息,
      isban: false, // 司机是否封禁  true:封禁  false:未封禁
      isShowAgreement: false, // 是否显示保密协议签订
    };
  }

  componentDidMount() {
    this.getFaceStatus();

    this.initMain();
  }

  render() {
    const {
      applyLeaveModelIsShow,
      driverCerStatus,
      driverCerData,
    } = this.state;

    return (
      <SafeAreaView style={styles.container}>
        <XMHeader
          style={{ borderBottomWidth: 0 }}
          renderLeft={() => {
            return (
              <Image
                source={sjfwText}
                style={{ width: px2dp(144), height: px2dp(38), marginLeft: px2dp(32) }}
                resizeMode='contain'
              />
            );
          }}
          renderRight={() => {
            return (
              <TouchableOpacity
                style={styles.headerRightContainer}
                activeOpacity={0.8}
                onPress={() => {
                  msg.emit('router: goToNext', {
                    routeName: 'RoleSwitch',
                  });
                }}
              >
                <LinearGradient
                  colors={['#FDCA85', '#EAA448']}
                  style={styles.headerRightContainer}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 0 }}
                >
                  <Text style={styles.headerRightText}>切换身份</Text>
                  <Image
                    source={iconChangeWhite}
                    style={styles.headerChangeImg}
                    resizeMode='contain'
                  />
                </LinearGradient>
              </TouchableOpacity>
            );
          }}
          renderTitle={() => {
            return <Text style={{ color: fontColorDeepRed }}>{_.checkCurrentEnv()}</Text>;
          }}
        />
        <View style={styles.container}>
          {/* 协议 */}
          {this.showAgreementView()}
          <InsuranceEntrance driverCerStatus={driverCerStatus} driverCerData={driverCerData} />
          {/* 主体内容 */}
          {this._renderContent()}

          {/* 请假弹框 */}
          {applyLeaveModelIsShow && (
            <ApplyLeave onChangeModal={(obj) => this._onChangeModal(obj)} />
          )}

          {/* {__DEV__ && <TouchableOpacity
            onPress={() => {
              msg.emit('router: goToNext', {
                routeName: 'ListViewDemo',
              });
            }}
            style={styles.test}
          >
            <Text>test</Text>
          </TouchableOpacity>} */}
        </View>
      </SafeAreaView>
    );
  }

  _renderContent = () => {
    const {
      driverCerStatus,
      driverCerData,
      driverCarList,
      isLeave,
      driverState,
      carState,
      leaveId,
      canLeave,
      isban,
    } = this.state;
    // 1. 是否认证完成
    if (driverCerStatus === 0 || driverCerStatus === 1 || driverCerStatus === 3) {
      // 未完成
      return (
        <DriverUncer
          driverCerStatus={driverCerStatus}
          driverCerData={driverCerData}
        />
      );
    }
    // 2.如果认证完成，是否有车辆
    if (driverCerStatus === 2 && !driverCarList) {
      // 无车
      return <DriverUnTruck />;
    }
    // 3.请假中，暂停接单,
    if (
      !isLeave &&
      driverCerStatus === 2 &&
      driverCarList
    ) {
      return <DriverOutline
        leaveId={leaveId}
        driverState={driverState}
        carState={carState}
      />;
    }
    // 4.是否被封禁
    if (isban) {
      return <DriverBan
        relieveTime={driverCerData.relieveTime}
        banReason={driverCerData.banReason}
      />;
    }

    // 接单列表
    if (driverCerStatus === 2 && driverCarList && isLeave && !isban) {
      return <OrderList
        canLeave={canLeave}
        onChangeModal={(obj) => this._onChangeModal(obj)}
        initMain={() => this.initMain()}
      />;
    }

    return <XMEmpty emptyImg={empty03} desc='网络错误' boxStyle={{ marginTop: px2dp(200) }} />;
  };

  // 初始化
  initMain = () => {
    // 获取司机认证状态
    api.supply.getDriverCer().then((res) => {
      if (res.success) {
        const isban = !!(res.data.state === 2 && res.data.status && res.data.status.code === 3);
        this.setState({
          driverCerStatus: res.data.state,
          driverCerData: res.data,
          isban: isban,
        }, () => {
          // 保密协议签署状态
          api.user.driverGetAgreement().then((res2) => {
            const { driverCerStatus } = this.state;
            if (res2.success) {
              if (res2.data === false && driverCerStatus === 2) {
                this.setState({ isShowAgreement: true });
              }
            }
          });
        });
      }
    });
    // 获取司机车辆
    api.supply.getDriverCarDetail().then((res) => {
      if (res.success) {
        this.setState({
          driverCarList: res.data,
        });
      }
    });
    // 查看请假
    api.supply.getDriverState().then((res) => {
      if (res.data) {
        // 司机或者汽车请假
        if (res.data.driverState === 2 || res.data.carState === 2) {
          this.setState({
            isLeave: false,
            driverState: res.data.driverState,
            carState: res.data.carState,
          });
        } else {
          this.setState({
            isLeave: true,
            driverState: res.data.driverState,
            carState: res.data.carState,
          });
        }
      }
    });
  };

  getFaceStatus = () => {
    api.supply.getDriverFace().then((res) => {
      if (res.success && res.data) {
        this.setState(
          {
            hasFace: true,
          },
          () => {
            this.faceInput();
          },
        );
      } else {
        this.setState(
          {
            hasFace: false,
          },
          () => {
            this.faceInput();
          },
        );
      }
    });
  };

  faceInput = () => {
    const { hasFace, driverCerStatus } = this.state;
    if (!hasFace && driverCerStatus === 3) {
      msg.emit('app:messageBox', {
        isVisible: true,
        text: '检测到您还没有录入人脸信息为保证正常使用车载设备，请前往录入',
        okText: '立即录入',
        cancelText: '',
        headerCancel: true,
        okBtnBg: true,
        imgSource: require('@/images/wl/face-input.png'),
        okFn: () => {
          msg.emit('router: goToNext', { routeName: 'FaceInput' });
        },
      });
    }
  };

  // 改变弹框显示隐藏,相关数据
  _onChangeModal = ({ type, val }) => {
    this.setState({ [type]: val });
  };

  // 保密协议提醒
  showAgreementView = () => {
    const { isShowAgreement } = this.state;
    return isShowAgreement ? (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => {
          msg.emit('router: goToNext', {
            routeName: 'DriverAgreementSign',
            routerFrom: 'DriverMain',
          });
        }}
      >
        <View style={styles.agreementView}>
          <TouchableOpacity
            style={styles.agreementClose}
            onPress={() => {
              this.setState({ isShowAgreement: false });
            }}
          >
            <Image
              source={iconCloseOrange}
              style={styles.agreementCloseIcon}
            />
          </TouchableOpacity>
          <Text style={styles.agreementText}>
            为保证正常接单，请先签约《司机保密协议》
          </Text>
          <Submit
            text='去签约'
            boxStyle={{
              width: px2dp(110),
              height: px2dp(44),
              borderRadius: px2dp(22),
              borderWidth: 1 / PixelRatio.get(),
              borderColor: '#E97B31',
              backgroundColor: '#FEF7EA'
            }}
            btnStyle={{}}
            btnTextStyle={{
              fontSize: px2dp(24),
              color: '#E97B31'
            }}
            onClick={() => {
              msg.emit('router: goToNext', {
                routeName: 'DriverAgreementSign',
                routerFrom: 'DriverMain',
              });
            }}
          />
          <Image
            source={wlAgreementRightArrow}
            style={styles.agreementRightIcon}
          />
        </View>
      </TouchableOpacity>
    ) : null;
  };
}

const styles = StyleSheet.create({
  container: {
    height: '100%',
    width: '100%',
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center'
  },
  header: {
    width: screenWidth,
    height: px2dp(217),
    backgroundColor: mainBgColorWhite,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: px2dp(60),
  },
  headerRightContainer: {
    width: px2dp(188),
    height: px2dp(48),
    borderTopLeftRadius: px2dp(24),
    borderBottomLeftRadius: px2dp(24),
    overflow: 'hidden',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  headerRightText: {
    fontSize: px2dp(28),
    fontWeight: 'bold',
    color: fontColorWhite,
  },
  headerChangeImg: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(8),
  },
  agreementView: {
    height: px2dp(36 * 2),
    width: '100%',
    backgroundColor: '#FEF7EA',
    flexDirection: 'row',
    alignItems: 'center',

  },
  agreementClose: {
    justifyContent: 'center',
    alignItems: 'center',
    width: px2dp(36 * 2),
    height: px2dp(36 * 2),
    // marginLeft: px2dp(16 * 2),
  },
  agreementText: {
    color: '#E97B31',
    fontSize: px2dp(12 * 2),
    // marginLeft: px2dp(12 * 2),
    flex: 1,
  },
  agreementRightIcon: {
    width: px2dp(12 * 2),
    height: px2dp(12 * 2),
    marginRight: px2dp(16 * 2),
  },
  agreementCloseIcon: {
    width: px2dp(12 * 2),
    height: px2dp(12 * 2),
  },
  test: {
    position: 'absolute',
    top: 200,
    right: 30,
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: 'pink',
    justifyContent: 'center',
    alignItems: 'center',
  },

});
